<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">{{ isEdit ? '编辑收货地址' : '新增收货地址' }}</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 表单内容 -->
    <view class="form-container">
      <view class="form-item">
        <text class="form-label">收货人</text>
        <input 
          class="form-input" 
          type="text" 
          v-model="formData.receiverName" 
          placeholder="请输入收货人姓名"
          :class="{ 'input-error': errors.receiverName }"
        />
        <text v-if="errors.receiverName" class="error-text">{{ errors.receiverName }}</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">手机号码</text>
        <input 
          class="form-input" 
          type="number" 
          v-model="formData.receiverPhone" 
          placeholder="请输入手机号码"
          maxlength="11"
          :class="{ 'input-error': errors.receiverPhone }"
        />
        <text v-if="errors.receiverPhone" class="error-text">{{ errors.receiverPhone }}</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">所在地区</text>
        <view 
          class="region-picker"
          @click="showRegionPicker"
          :class="{ 'input-error': errors.region }"
        >
          <text v-if="formData.province && formData.city">
            {{ formData.province }} {{ formData.city }} {{ formData.district }}
          </text>
          <text v-else class="placeholder-text">请选择所在地区</text>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>
        <text v-if="errors.region" class="error-text">{{ errors.region }}</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">详细地址</text>
        <textarea 
          class="form-textarea" 
          v-model="formData.detailAddress" 
          placeholder="请输入详细地址，如街道、门牌号等"
          :class="{ 'input-error': errors.detailAddress }"
        />
        <text v-if="errors.detailAddress" class="error-text">{{ errors.detailAddress }}</text>
      </view>
      
      <view class="form-item switch-item">
        <text class="form-label">设为默认地址</text>
        <switch 
          :checked="formData.isDefault" 
          @change="handleDefaultChange" 
          color="#FF8C42"
        />
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer">
      <button 
        class="save-btn" 
        :disabled="isSubmitting" 
        @click="saveAddress"
      >
        {{ isSubmitting ? '保存中...' : '保存' }}
      </button>
    </view>
    
    <!-- 地区选择器 -->
    <uni-popup ref="regionPopup" type="bottom">
      <view class="region-popup">
        <view class="region-header">
          <text class="cancel-btn" @click="cancelRegionSelect">取消</text>
          <text class="title">选择地区</text>
          <text class="confirm-btn" @click="confirmRegionSelect">确定</text>
        </view>
        <picker-view 
          class="region-picker-view" 
          :value="regionValue" 
          @change="handleRegionChange"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in provinces" :key="index">
              {{ item }}
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in cities" :key="index">
              {{ item }}
            </view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in districts" :key="index">
              {{ item }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useUserStore } from '@/store/user';
import http from '@/utils/http/http.js';

const userStore = useUserStore();
const statusBarHeight = ref(0);
const isEdit = ref(false);
const addressId = ref(null);
const isSubmitting = ref(false);
const regionPopup = ref(null);

// 表单数据
const formData = reactive({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: false
});

// 表单错误信息
const errors = reactive({
  receiverName: '',
  receiverPhone: '',
  region: '',
  detailAddress: ''
});

// 地区选择器相关
const regionValue = ref([0, 0, 0]);
const tempRegion = reactive({
  province: '',
  city: '',
  district: ''
});

// 模拟地区数据 - 实际项目中应该从后端获取或使用完整的地区数据
const provinces = ref(['广东省', '北京市', '上海市', '浙江省', '江苏省']);
const citiesMap = {
  '广东省': ['广州市', '深圳市', '东莞市', '佛山市', '珠海市'],
  '北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区'],
  '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区'],
  '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市'],
  '江苏省': ['南京市', '苏州市', '无锡市', '常州市', '南通市']
};
const districtsMap = {
  '广州市': ['天河区', '越秀区', '海珠区', '荔湾区', '白云区'],
  '深圳市': ['南山区', '福田区', '罗湖区', '宝安区', '龙岗区'],
  '杭州市': ['西湖区', '上城区', '下城区', '江干区', '拱墅区'],
  '南京市': ['玄武区', '秦淮区', '建邺区', '鼓楼区', '浦口区'],
  // 其他城市的区数据...
};

// 计算属性：当前可选城市列表
const cities = computed(() => {
  const province = provinces.value[regionValue.value[0]];
  return citiesMap[province] || [];
});

// 计算属性：当前可选区列表
const districts = computed(() => {
  const province = provinces.value[regionValue.value[0]];
  const city = citiesMap[province]?.[regionValue.value[1]];
  return districtsMap[city] || [];
});

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight || 0;
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 处理默认地址切换
const handleDefaultChange = (e) => {
  formData.isDefault = e.detail.value;
};

// 显示地区选择器
const showRegionPicker = () => {
  // 保存当前选择，用于取消时恢复
  tempRegion.province = formData.province;
  tempRegion.city = formData.city;
  tempRegion.district = formData.district;
  
  // 根据当前选择设置选择器的值
  if (formData.province) {
    const provinceIndex = provinces.value.findIndex(p => p === formData.province);
    if (provinceIndex !== -1) {
      regionValue.value[0] = provinceIndex;
      
      if (formData.city) {
        const cityIndex = citiesMap[formData.province].findIndex(c => c === formData.city);
        if (cityIndex !== -1) {
          regionValue.value[1] = cityIndex;
          
          if (formData.district) {
            const districtIndex = districtsMap[formData.city].findIndex(d => d === formData.district);
            if (districtIndex !== -1) {
              regionValue.value[2] = districtIndex;
            }
          }
        }
      }
    }
  }
  
  regionPopup.value.open();
};

// 处理地区选择变化
const handleRegionChange = (e) => {
  regionValue.value = e.detail.value;
  
  // 更新临时选择
  const province = provinces.value[regionValue.value[0]];
  tempRegion.province = province;
  
  const cityList = citiesMap[province] || [];
  tempRegion.city = cityList[regionValue.value[1]] || '';
  
  const districtList = districtsMap[tempRegion.city] || [];
  tempRegion.district = districtList[regionValue.value[2]] || '';
};

// 取消地区选择
const cancelRegionSelect = () => {
  regionPopup.value.close();
};

// 确认地区选择
const confirmRegionSelect = () => {
  formData.province = tempRegion.province;
  formData.city = tempRegion.city;
  formData.district = tempRegion.district;
  
  // 清除地区错误提示
  errors.region = '';
  
  regionPopup.value.close();
};

// 表单验证
const validateForm = () => {
  let isValid = true;
  
  // 清除所有错误
  Object.keys(errors).forEach(key => {
    errors[key] = '';
  });
  
  // 验证收货人
  if (!formData.receiverName.trim()) {
    errors.receiverName = '请输入收货人姓名';
    isValid = false;
  }
  
  // 验证手机号
  if (!formData.receiverPhone.trim()) {
    errors.receiverPhone = '请输入手机号码';
    isValid = false;
  } else if (!/^1\d{10}$/.test(formData.receiverPhone.trim())) {
    errors.receiverPhone = '请输入正确的手机号码';
    isValid = false;
  }
  
  // 验证地区
  if (!formData.province || !formData.city) {
    errors.region = '请选择所在地区';
    isValid = false;
  }
  
  // 验证详细地址
  if (!formData.detailAddress.trim()) {
    errors.detailAddress = '请输入详细地址';
    isValid = false;
  }
  
  return isValid;
};

// 保存地址
const saveAddress = async () => {
  if (!validateForm()) {
    uni.showToast({
      title: '请完善表单信息',
      icon: 'none'
    });
    return;
  }
  
  if (!userStore.isLoggedIn || !userStore.token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    const addressData = {
      receiverName: formData.receiverName,
      receiverPhone: formData.receiverPhone,
      province: formData.province,
      city: formData.city,
      district: formData.district || '',
      detailAddress: formData.detailAddress,
      isDefault: formData.isDefault ? 1 : 0
    };
    
    let response;
    
    if (isEdit.value) {
      // 更新地址
      response = await http.put(`/api/address/${addressId.value}`, addressData, {
        header: {
          'Authorization': `Bearer ${userStore.token}`
        }
      });
    } else {
      // 新增地址
      response = await http.post('/api/address/add', addressData, {
        header: {
          'Authorization': `Bearer ${userStore.token}`
        }
      });
    }
    
    if (response.code === 200) {
      uni.showToast({
        title: isEdit.value ? '更新地址成功' : '添加地址成功',
        icon: 'success'
      });
      
      // 通知地址列表页刷新
      uni.$emit('addressUpdated');
      
      // 返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: response.message || (isEdit.value ? '更新地址失败' : '添加地址失败'),
        icon: 'none'
      });
    }
  } catch (error) {
    console.error(isEdit.value ? '更新地址失败:' : '添加地址失败:', error);
    uni.showToast({
      title: isEdit.value ? '更新地址失败，请重试' : '添加地址失败，请重试',
      icon: 'none'
    });
  } finally {
    isSubmitting.value = false;
  }
};

// 获取地址详情
const fetchAddressDetail = async (id) => {
  try {
    const response = await http.get(`/api/address/${id}`, {
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    if (response.code === 200 && response.data) {
      const address = response.data;
      
      // 填充表单数据
      formData.receiverName = address.receiverName;
      formData.receiverPhone = address.receiverPhone;
      formData.province = address.province;
      formData.city = address.city;
      formData.district = address.district;
      formData.detailAddress = address.detailAddress;
      formData.isDefault = address.isDefault === 1;
    } else {
      uni.showToast({
        title: response.message || '获取地址详情失败',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } catch (error) {
    console.error('获取地址详情失败:', error);
    uni.showToast({
      title: '获取地址详情失败，请重试',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
};

// 页面加载
onMounted(() => {
  getStatusBarHeight();
  
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage && currentPage.options) {
    const id = currentPage.options.id;
    if (id) {
      isEdit.value = true;
      addressId.value = id;
      fetchAddressDetail(id);
    }
  }
});
</script>

<style>
.container {
  padding-bottom: 120rpx;
  background-color: #FFF9F2;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #FFE6CC;
  padding: 0 20rpx;
}

.nav-back, .nav-right {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 表单容器 */
.form-container {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  background-color: #F8F8F8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.form-textarea {
  width: 100%;
  height: 160rpx;
  background-color: #F8F8F8;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.region-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 80rpx;
  background-color: #F8F8F8;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.placeholder-text {
  color: #999;
}

.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-error {
  border: 1rpx solid #FF5252;
}

.error-text {
  font-size: 24rpx;
  color: #FF5252;
  margin-top: 8rpx;
}

/* 底部按钮 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.save-btn {
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.3);
}

/* 地区选择器弹窗 */
.region-popup {
  background-color: #fff;
  border-top-left-radius: 16rpx;
  border-top-right-radius: 16rpx;
  overflow: hidden;
}

.region-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.cancel-btn {
  font-size: 28rpx;
  color: #999;
}

.title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.confirm-btn {
  font-size: 28rpx;
  color: #FF8C42;
  font-weight: bold;
}

.region-picker-view {
  height: 400rpx;
  width: 100%;
}

.picker-item {
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
}
</style>
